# -*-  codeing:utf-8 -*-
import random

from ChanDaoBase import cdbase
import re
from datetime import datetime
import random

class ChanDaoUtils(cdbase):
    def __init__(self, base_url):
        super(ChanDaoUtils, self).__init__(base_url)

    def compute_bug(self, html_string):
        """
        按统计未关闭，级别，所属人  的bug分布
        """
        # 初始化记录字典
        def demo(level, username):
            # 判断bug，对应级别和总数+1
            user_dict[username][level] += 1
            user_dict[username][0] = +1
            user_dict["总计"][level] = +1
            user_dict["总计"][0] += 1
            for key,value in group_dict.items():
                if username in value :
                    user_dict[key[level]] += 1
                    user_dict[key] += 1
                    break
            else:
                print("没找到组： %s"% username)

        # 字典 ，组织架构图
        group_dict = {"几何组":["","22" ]}

        # 初始化记录字典
        user_dict = {"总计": [0, 0, 0, 0, 0],"xx组":[0,0,0,0]}

        bug_trs = self.parser_tr(html_string)
        for bug_doc in bug_trs:
            try:
                username = bug_doc.xpath("descendant::span[@class='text-primary']")[0].text  # 在谁
            except:
                username = bug_doc.xpath("descendant::span[@class='text-red']")[0].text
            level = bug_doc.xpath("descendant::span[@class='label-severity']")[0].text
            level_int = int(level)
            if username not in user_dict:
                user_dict[username] = [0, 0, 0, 0, 0]
                demo(level_int, username)
            else:
                demo(level_int, username)
        # 写文件
        filename = "1.csv"
        self.write_file(filename, "姓名,总数,1级,2级,3级,4级")
        for key, value in user_dict.items():
            write_string = key + "," + str(value).replace("[", "").replace("]", "") + "\n"
            self.write_file(filename, write_string, "a+")
        print("生成文件名：%s" % filename)

    def compute_closed_bug(self):
        """
        统计时间段内的关闭bug，激活bug，新增bug
        """
        write_string_list = []
        timestamp = input("请输入日期（格式：2021-07-21）：")
        searchdict = {"andOr1": "AND",
                      "field1": "closedData",
                      "operator1": ">=",
                      "value": timestamp}
        print("set search bug : 搜索关闭的bug")
        text = self.search_bug(searchdict)
        bug_trs = self.parser_tr(text)
        close_ID_list = []
        for bug in bug_trs:
            bug_id = bug.attrib["data-id"]
            close_ID_list.append(bug_id)
        write_string_list.extend(["已关闭bug数：%d" % len(close_ID_list), str(close_ID_list)])

        # 筛选激活
        searchdict = {"andOr1": "AND",
                      "field1": "lastEditedDate",
                      "operator1": ">=",
                      "value1": timestamp,
                      "andOr2": "AND",
                      "field2": "status",
                      "operator2": "=",
                      "value2": "active",
                      "andOr3": "AND",
                      "field3": "activatedCount",
                      "operator3": ">=",
                      "value3": "1"}
        text = self.search_bug(searchdict)
        bug_trs = self.parser_tr(text)
        reopen_ID_list = []
        for bug in bug_trs:
            bug_id = bug.attrib["data-id"]
            reopen_ID_list.append(bug_id)
        write_string_list.extend(["激活bug数：%d " % len(reopen_ID_list), str(reopen_ID_list)])

        # 筛选新增
        searchdict = {"andOr1": "AND",
                      "field1": "openedDate",
                      "operator1": ">=",
                      "value1": timestamp}
        text = self.search_bug(searchdict)
        bug_trs = self.parser_tr(text)
        new_ID_list = []
        for bug in bug_trs:
            bug_id = bug.attrib["data-id"]
            reopen_ID_list.append(bug_id)
        write_string_list.extend(["新增bug数：%d " % len(new_ID_list), str(new_ID_list)])
        wirte_string = "\n".join(write_string_list)
        print(wirte_string)
        self.write_file("2.txt", wirte_string, "w+")
        print("已记录到文件:2.txt")

    def get_case_record_in_module(self, num, timestamp=None):
        """
        查询各模块用例的总执行次数
        num : 模块id
        timestamp : 大于此时间的记录  "2022-01-01"
        """
        searchdict = {"andOr1": "AND",
                      "field1": "module",
                      "operator1": "belong",
                      "value1": num}
        total_record = 0
        case_trs = self.search_case(searchdict)
        for case in case_trs:
            caseid = case.attrib["data-id"]
            records = self.get_case_result_record(num=caseid, timestamp=timestamp)
            case_record = int(records[2])
            total_record += case_record
        return total_record

    def generate_bug_in_module(self, searchdict=None):
        if searchdict != None:
            searchdict.update({"andOr1": "AND",
                               "field1": "module",
                               "operator1": "belong",
                               "value1": ""})
        else:
            searchdict = {"andOr1": "AND",
                          "field1": "module",
                          "operator1": "belong",
                          "value1": ""}
        module_dir = self.get_module_list()
        recompile = re.compile("\d{1,4}")
        module_bug_list = []
        # bug num
        for key, value in module_dir["bug"].items():
            num = re.search(recompile, key).group()
            searchdict["value1"] = num
            print("模块ID：%s" % num)
            self.set_search_query(searchdict, searchtype="bug")
            path = "bug-browse-1-0-bySearch-myQueryID.html"
            con = self.session.get(url=self.base_url + path)
            bugtotal = self.get_total_num(con.text)

            module_bug_list.append([key, value, bugtotal])
        return module_bug_list

    def generate_case_in_module(self, searchdict=None, recordstamp=None):
        if searchdict != None:
            searchdict.update({"andOr1": "AND",
                               "field1": "module",
                               "operator1": "belong",
                               "value1": ""})
        else:
            searchdict = {"andOr1": "AND",
                          "field1": "module",
                          "operator1": "belong",
                          "value1": ""}
        module_dir = self.get_module_list()
        recompile = re.compile("\d{1,4}")
        module_case_list = []
        # case num
        for key, value in module_dir["case"].items():
            num = re.search(recompile, key).group()
            searchdict["value1"] = num
            print("模块ID：%s" % num)
            self.set_search_query(searchdict, searchtype="testcase")
            path = "testcase-browse-1-0-bySearch-myQueryID.html"
            con = self.session.get(url=self.base_url + path)
            casetotal = self.get_total_num(con.text)

            # record num
            if recordstamp:
                total_record = self.get_case_record_in_module(num, timestamp=recordstamp)
            else:
                total_record = self.get_total_record(num)
            module_case_list.append([key, value, casetotal, str(total_record)])
        return module_case_list

    def half_month_generate(self):
        """
        根据日期统计各模块数据
        """
        timeinput = input("请输入日期（格式：2021-07-21）：")
        searchdict = {"andOr2": "AND",
                      "field2": "openedDate",
                      "operator2": ">=",
                      "value2": timeinput}
        module_case_list1 = self.generate_case_in_module(searchdict, recordstamp=timeinput)
        searchdict = {"andOr2": "AND",
                      "field2": "lastEditedDate",
                      "operator2": ">=",
                      "value2": timeinput}
        module_case_list2 = self.generate_case_in_module(searchdict)
        new_module_case_list = []
        for index, module in enumerate(module_case_list1):
            module.insert(3, module_case_list2[index][2])
            new_module_case_list.append(module)
        new_module_bug_list = self.generate_bug_in_module(searchdict)
        return new_module_case_list, new_module_bug_list

    def generate_data(self):
        # 半月
        new_module_case_list, new_module_bug_list = self.half_month_generate()
        # 总数
        module_case_list = self.generate_case_in_module()
        module_bug_list = self.generate_bug_in_module()
        self.write_file("半月数据.csv", "\n\n模块ID,名称,用例总数,总执行条数\n", "w")
        for module in module_case_list:
            write_string = ",".join(module)
            self.write_file("半月数据.csv", write_string, "a")
        self.write_file("半月数据.csv", "\n\n模块ID,名称,bug总数\n", "a")
        for module in module_bug_list:
            write_string = ",".join(module)
            self.write_file("半月数据.csv", write_string, "a")
        self.write_file("半月数据.csv", "\n\n模块ID,名称,半月新增用例,半月修改用例\n", "a")
        for module in new_module_case_list:
            write_string = ",".join(module)
            self.write_file("半月数据.csv", write_string, "a")
        self.write_file("半月数据.csv", "\n\n模块ID,名称,半月新增bug\n", "a")
        for module in new_module_bug_list:
            write_string = ",".join(module)
            self.write_file("半月数据.csv", write_string, "a")
        print("完成统计，同目录下csv文件")

    def random_assign(self,taskid,users):
        case_id_list = self.get_task_cases(taskid)

        part_num = len(case_id_list ) // len(users)
        yu = len(case_id_list) % len(users)
        random.shuffle(case_id_list)
        random.shuffle(users)
        for index ,user in enumerate(users):
            user_cases = case_id_list[index * part_num:(index+1) * part_num]
            print(user_cases)
            if yu > index:
                user_cases.append(case_id_list[-(index+1)])
            print(user)
            self.assign_cases(taskid=taskid,user=user,caselist=user_cases)

if __name__ == "__mian__":
    aitem = ChanDaoUtils("http://123.123.123.123:8080/zentao/")
    aitem.login(username="123", passwd="123")
    aitem.enter_qa()

    aitem.generate_data()
